<?php

namespace WebmanGrpc\Initializer;

use WebmanGrpc\Pool\ConnectionPool;
use WebmanGrpc\Serialization\SerializationOptimizer;
use WebmanGrpc\Memory\MemoryManager;
use WebmanGrpc\Module\ModuleManager;
use WebmanGrpc\Event\EventBus;
use WebmanGrpc\Event\LifecycleEventManager;

/**
 * 初始化器
 * 
 * 负责初始化gRPC扩展包的各个组件
 */
class Initializer
{
    /**
     * 是否已初始化
     * @var bool
     */
    protected static bool $initialized = false;
    
    /**
     * 初始化配置
     * @var array
     */
    protected static array $config = [];
    
    /**
     * 初始化gRPC扩展包
     * 
     * @param array $config 配置选项
     * @return void
     */
    public static function initialize(array $config = []): void
    {
        if (self::$initialized) {
            return;
        }
        
        self::$config = array_merge(self::getDefaultConfig(), $config);
        
        // 初始化连接池
        self::initializeConnectionPool();
        
        // 初始化序列化优化器
        self::initializeSerializationOptimizer();
        
        // 初始化内存管理器
        self::initializeMemoryManager();
        
        // 初始化模块管理器
        self::initializeModuleManager();
        
        // 初始化事件总线
        self::initializeEventBus();
        
        // 初始化生命周期事件管理器
        self::initializeLifecycleEventManager();
        
        self::$initialized = true;
    }
    
    /**
     * 获取默认配置
     * 
     * @return array 默认配置
     */
    protected static function getDefaultConfig(): array
    {
        return [
            'connection_pool' => [
                'max_connections' => 10,
                'max_lifetime' => 300,  // 5分钟
                'health_check_interval' => 30,  // 30秒
                'health_check_timeout' => 5,  // 5秒
                'leak_detection_interval' => 60,  // 60秒
                'leak_detection_threshold' => 300,  // 5分钟
                'warm_up_connections' => 2,
            ],
            'serialization' => [
                'lite_mode' => false,
                'pool_enabled' => true,
                'cache_enabled' => true,
                'pool_config' => [
                    'max_size' => 100,
                    'min_size' => 5,
                ],
                'cache_size' => 1000,
            ],
            'memory' => [
                'memory_limit' => 0,  // 0表示使用PHP配置的限制
                'warning_threshold' => 0,  // 0表示为限制的80%
                'max_history_size' => 100,
                'monitoring_enabled' => false,
                'monitoring_interval' => 5,
            ],
            'stream_processor' => [
                'max_memory_usage' => 50 * 1024 * 1024,  // 50MB
                'batch_size' => 100,
                'memory_monitoring_enabled' => true,
            ],
            'event' => [
                'history_enabled' => false,
                'max_history_size' => 100,
            ],
            'modules' => [
                'enabled' => [],
                'configs' => [],
            ],
        ];
    }
    
    /**
     * 初始化连接池
     * 
     * @return void
     */
    protected static function initializeConnectionPool(): void
    {
        $connectionPool = ConnectionPool::getInstance();
        $connectionPool->initialize(self::$config['connection_pool']);
    }
    
    /**
     * 初始化序列化优化器
     * 
     * @return void
     */
    protected static function initializeSerializationOptimizer(): void
    {
        SerializationOptimizer::initialize(self::$config['serialization']);
    }
    
    /**
     * 初始化内存管理器
     * 
     * @return void
     */
    protected static function initializeMemoryManager(): void
    {
        MemoryManager::initialize(self::$config['memory']);
        
        // 添加内存警告回调
        MemoryManager::addCallback('memory_warning', function ($data) {
            error_log("Memory usage warning: {$data['current']} bytes (threshold: {$data['threshold']} bytes)");
        });
        
        // 添加内存限制回调
        MemoryManager::addCallback('memory_limit_exceeded', function ($data) {
            error_log("Memory limit exceeded: {$data['current']} bytes (limit: {$data['limit']} bytes)");
            
            // 尝试释放内存
            $freed = MemoryManager::tryFreeMemory();
            error_log("Freed {$freed} bytes of memory");
        });
    }
    
    /**
     * 初始化模块管理器
     * 
     * @return void
     */
    protected static function initializeModuleManager(): void
    {
        // 这里可以注册默认模块
        // 例如：
        // $moduleManager = ModuleManager::getInstance();
        // $moduleManager->register(new SomeModule());
        
        // 加载启用的模块
        $enabledModules = self::$config['modules']['enabled'];
        $moduleConfigs = self::$config['modules']['configs'];
        
        if (!empty($enabledModules)) {
            ModuleManager::loadAll($moduleConfigs);
        }
    }
    
    /**
     * 初始化事件总线
     * 
     * @return void
     */
    protected static function initializeEventBus(): void
    {
        $eventBus = EventBus::getInstance();
        
        if (self::$config['event']['history_enabled']) {
            $eventBus->enableHistory(self::$config['event']['max_history_size']);
        }
    }
    
    /**
     * 初始化生命周期事件管理器
     * 
     * @return void
     */
    protected static function initializeLifecycleEventManager(): void
    {
        $lifecycleEventManager = LifecycleEventManager::getInstance();
        
        // 添加默认生命周期钩子
        $lifecycleEventManager->addHook('shutdown', function () {
            // 清理连接池
            $connectionPool = ConnectionPool::getInstance();
            $connectionPool->closeAll();
            
            // 清空序列化缓存
            SerializationOptimizer::clearCache();
        }, 0);
    }
    
    /**
     * 检查是否已初始化
     * 
     * @return bool 是否已初始化
     */
    public static function isInitialized(): bool
    {
        return self::$initialized;
    }
    
    /**
     * 获取配置
     * 
     * @param string|null $key 配置键，为null时返回所有配置
     * @return mixed 配置值
     */
    public static function getConfig(?string $key = null)
    {
        if ($key === null) {
            return self::$config;
        }
        
        return self::$config[$key] ?? null;
    }
    
    /**
     * 获取初始化状态
     * 
     * @return array 初始化状态
     */
    public static function getStatus(): array
    {
        $status = [
            'initialized' => self::$initialized,
            'components' => [],
        ];
        
        if (self::$initialized) {
            // 连接池状态
            $connectionPool = ConnectionPool::getInstance();
            $status['components']['connection_pool'] = $connectionPool->getStats();
            
            // 序列化优化器状态
            $status['components']['serialization'] = SerializationOptimizer::getStats();
            
            // 内存管理器状态
            $status['components']['memory'] = MemoryManager::getMemoryStats();
            
            // 模块管理器状态
            $status['components']['modules'] = ModuleManager::getAllModuleStatus();
            
            // 事件总线状态
            $eventBus = EventBus::getInstance();
            $status['components']['event_bus'] = $eventBus->getStats();
            
            // 生命周期事件管理器状态
            $lifecycleEventManager = LifecycleEventManager::getInstance();
            $status['components']['lifecycle_events'] = $lifecycleEventManager->getStats();
        }
        
        return $status;
    }
}